<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/10
 * Time: 9:45
 */

namespace app\admin\controller;


use QiniuUpload\QiNiuUpload;
use think\Cache;
use think\Controller;
use think\Session;
use EasyWeChat\Factory;

class BaseController extends Controller
{
    public function stopNow()
    {

    }

    public function _initialize()
    {
//      过滤不需要登陆的行为
        if(in_array(request()->action(),array('login','logout'))){

        }else{
//            $action = request()->module().'/'.request()->controller().'/'.request()->action();
            if(Session::get('admin')){
//                节点控制认证
                $Auth = new \auth\Auth();
                if(!$Auth->check(request()->controller().'/'.request()->action(), session::get('admin'))){
                    $this->error('您没有权限',$_SERVER['HTTP_REFERER'],'','1');
                }
            }else{
                $this->error('请先登录','Admin/Login/login','',1);
            }
        }
    }

    //获取七牛token
    public function uptoken()
    {
        $file = new QiNiuUpload();
        $token = $file->uptoken();
        return $token;
    }

    /*
     * @params  缓存名称，目前支付L，微信参数：wxconfig
     * @isupdate 是否更新缓存
     * @model   模型名称
     */
    public function getSetting($param = 'wxconfig',$model = 'Wxsetting',$data = false)
    {
        //查询缓存
        $cache = Cache::get($param);
        $m = model($model);
        //缓存不存在
        if(!$cache){
            //重新查询存储到缓存
            $result = $m->find();
            if(empty($result)){
                return;
            }
            $result = $result->toArray();
            Cache::set($param,$result);
        }
        //如果传递有数组，则为更新
        if($data){
            $res = $m->find();
            if(!is_array($data)) {
                $data = $data->toArray();
            }
            $res->isUpdate(true)->save($data);
            $res = $m->find();
            Cache::set($param,$res);
        }
        return Cache::get($param);
    }

    //获取实例化的小程序--结合easywechat
    public function getMini()
    {
        $data = $this->getSetting();
        if(!$data['appid'] || !$data['appsecret']) return ajaxMsg(0,'获取配置信息失败');
        $config = [
            'app_id' => $data['appid'],
            'secret' => $data['appsecret'],
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => RUNTIME_PATH.'/log/wechat.log',
            ],
        ];
        return Factory::miniProgram($config);
    }
    
}